package fr.inserm.umr915.vcfserver.tool;


import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;





import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import fr.inserm.umr915.vcfserver.bio.berkeley.DatabaseManager;
import fr.inserm.umr915.vcfserver.bio.berkeley.Storage;




public class EnvironmentLoader
	{
	private static final Log LOG= LogFactory.getLog("fr.inserm.umr915");
	private Storage storage=new Storage();
	private Set<Short> useOnlyThoseDatabases=new HashSet<Short>();
	
	private void run() throws IOException
		{
		for(DatabaseManager<?> mgr: storage.getDatabaseManagers())
			{
			if(!useOnlyThoseDatabases.isEmpty() && !useOnlyThoseDatabases.contains(mgr.getId()))
				{
				LOG.info("skipping "+mgr.getName());
				continue;
				}
			LOG.info(mgr.getName());
			mgr.fill(storage);
			
			}
		LOG.info("start sync");
		this.storage.env.sync();
		LOG.info("end sync");
		}
	
	public static void main(String[] args)
		{
		EnvironmentLoader app=new EnvironmentLoader();
		try {
			File xmlConfig=null;
			int optind=0;
			while(optind<args.length)
				{
				if(args[optind].equals("-h"))
					{
					return;
					}
				else if(args[optind].equals("-x"))
					{
					xmlConfig=new File(args[++optind]);
					}
				else if(args[optind].equals("-i"))
					{
					app.useOnlyThoseDatabases.add(Short.parseShort(args[++optind]));
					}
				else if(args[optind].equals("--"))
					{
					optind++;
					break;
					}
				else if(args[optind].startsWith("-"))
					{
					System.err.println("Unnown option: "+args[optind]);
					return;
					}
				else
					{
					break;
					}
				++optind;
				}
			if(xmlConfig==null)
				{
				System.err.println("undefined xml config");
				return;
				}
			LOG.info(xmlConfig);
			XmlBeanFactory factory=new XmlBeanFactory(new FileSystemResource(xmlConfig));
			LOG.info(factory);
			File bdbHome=(File)factory.getBean("berkeley.db.home");
			LOG.info("File is "+bdbHome);
			bdbHome.mkdir();
			
			
			
			app.storage.open(factory, false);
			app.run();
			
			
			
			} 
		catch (Exception e)
			{
			e.printStackTrace();
			}
		finally
			{
			app.storage.close();
			}
		}
	}
